package com.huanbao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huanbao.entity.User;
import com.huanbao.mapper.UserMapper;
import com.huanbao.service.PersonalService;
import com.huanbao.util.ShiroUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

/**
 * <p>
 * 用户任务表 服务实现类
 * </p>
 *
 * @author zq
 * @since 2021-04-27
 */
@Service
public class PersonalServiceImpl implements PersonalService {

    @Resource
    private UserMapper userMapper;

    @Override
    public String savePicByFormData(MultipartFile file) throws IOException {

        Long id = ShiroUtil.getProfile().getId();
        // 图片存储路径
        String path = System.getProperty("user.dir") + "\\src\\main\\resources\\image";

        String originalFilename = file.getOriginalFilename();
        //防止上传为空
        assert null != originalFilename;
        String extendName = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = id + extendName;
        //更新数据库中user头像
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("id", id));
        user.setAvatar(path + "\\" + filename);
        userMapper.updateById(user);
        //图片上传在服务器本地
        File dir = new File(path, filename);
        file.transferTo(dir);
        //return url给前端
        return path + "\\" + filename;
    }

}
